<template>
  <div class="app-container">
    <img :src="testQrcode" alt="" />
    <!-- 数据统计 -->
    <el-card style="margin-bottom: 20px" body-style="width: 100%; display: flex; align-items: center">
      <!-- 左 -->
      <div class="statistics-content">
        <div class="statistic-item">
          <el-statistic title="总充电桩数">
            <template slot="formatter">{{ statisticInfo.siteNumber }}</template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="正常充电桩数">
            <template slot="formatter">
              {{ statisticInfo.normalSiteNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="故障充电桩数">
            <template slot="formatter">
              {{ statisticInfo.breakDownSiteNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="在线充电桩数">
            <template slot="formatter">
              {{ statisticInfo.onlineSiteNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="离线充电桩数">
            <template slot="formatter">
              {{ statisticInfo.offlineSiteNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="未注册充电桩数">
            <template slot="formatter">
              {{ statisticInfo.unRegisterSiteNumber }}
            </template>
          </el-statistic>
        </div>
      </div>
      <div class="divider"></div>
      <!-- 右 -->
      <div class="statistics-content">
        <div class="statistic-item">
          <el-statistic title="站点使用率">
            <template slot="formatter">
              {{
                statisticInfo.useNumber
                  ? statisticInfo.useNumber.toFixed(2) + "%"
                  : "-"
              }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="充电口总数">
            <template slot="formatter">
              {{ statisticInfo.stationNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="充电口空闲数">
            <template slot="formatter">
              {{ statisticInfo.idleStationNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="故障充电口数">
            <template slot="formatter">
              {{ statisticInfo.breakDownStationNumber }}
            </template>
          </el-statistic>
        </div>
        <div class="statistic-item">
          <el-statistic title="忙碌充电口数(近7天)">
            <template slot="formatter">
              {{ statisticInfo.busyStationNumber }}
            </template>
          </el-statistic>
        </div>
      </div>
    </el-card>

    <!-- 表格 -->
    <el-card>
      <!-- 筛选表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="queryParams.siteName" placeholder="请输入站点名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="editVisible = true"
            v-hasPermi="['charge:site:add']">新增</el-button>
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="globalChargeVisible = true"
            v-hasPermi="['charge:site:add']">全局配置充电策略</el-button>
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="globalTcpVisible = true"
            v-hasPermi="['charge:site:add']">全局配置系统设置</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="tableList">
        <el-table-column label="站点id" prop="id" width="200" />
        <el-table-column label="站点名称" prop="siteName" width="150" />
        <el-table-column label="行政区域" prop="region" width="120" />
        <el-table-column label="详细地址" prop="detailAddress" width="120" />
        <el-table-column label="充电桩总数" prop="siteNumber" width="120" />
        <el-table-column label="充电桩正常" prop="normalSiteNumber" width="120" />
        <el-table-column label="故障充电桩" prop="breakDownSiteNumber" width="120" />
        <el-table-column label="在线充电桩数" prop="onlineSiteNumber" width="120" />
        <el-table-column label="离线充电桩数" prop="offlineSiteNumber" width="120" />
        <el-table-column label="未注册充电桩" prop="unRegisterSiteNumber" width="120" />
        <el-table-column label="站点使用率" prop="useNumber" width="120">
          <template slot-scope="scope">
            <span>{{
              scope.row.useNumber ? scope.row.useNumber.toFixed(1) + "%" : "-"
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="260">
          <template slot-scope="scope" v-if="scope.row.roleId !== 1">
            <el-button size="mini" type="text" icon="el-icon-search" @click="toDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['charge:site:remove']">删除</el-button>
            <br />
            <el-button size="mini" type="text" icon="el-icon-download"
              @click="exportQrcode(scope.row)">导出设备二维码</el-button>
            <el-button size="mini" type="text" icon="el-icon-download"
              @click="exportQrcode2(scope.row)">导出充电口二维码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />
    </el-card>

    <!-- 新增站点 -->
    <EditModal title="新增站点" :data="siteData" :visible="editVisible" @success="onEditSuccess" @cancel="onEditCancel">
    </EditModal>

    <!-- 全局配置充电策略 -->
    <GlobalChargeModal title="全局配置充电策略" :visible="globalChargeVisible" @success="onGlobalChargeEditSuccess"
      @cancel="onGlobalChargeEditCancel"></GlobalChargeModal>

    <!-- 全局配置系统设置 -->
    <GlobalTcpConfig :visible="globalTcpVisible" @success="onGlobalTcpConfigEditSuccess"
      @cancel="onGlobalTcpConfigEditCancel"></GlobalTcpConfig>
  </div>
</template>

<script>
import EditModal from "./components/EditModal";
import GlobalChargeModal from "./components/GlobalChargeModal";
import GlobalTcpConfig from "./components/GlobalTcpConfig";
import {
  getListAPI,
  deleteAPI,
  getStatisticAPI,
  exportListAPI,
} from "@/api/charge/site";
import { getListAPI as getStationListAPI } from "@/api/charge/station";
import QRCode from "qrcode";
import { exportExcel, exportExcelFromAPI } from "@/utils/utils";

export default {
  name: "Site",
  components: { EditModal, GlobalChargeModal, GlobalTcpConfig },
  data() {
    return {
      testQrcode: "",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],

      // 编辑弹窗展示
      editVisible: false,
      globalChargeVisible: false,
      globalTcpVisible: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        siteName: "",
      },

      // 站点统计数据
      statisticInfo: {},

      siteData: {},
    };
  },
  created() {
    this.getList();
    this.getStatistic();
  },
  methods: {
    exportData() {
      exportExcelFromAPI("/charge/site/list/export", {
        pageNum: 1,
        pageSize: 10000,
        siteName: this.queryParams.siteName || '',
      });
      return false;
      exportExcel({
        data: this.formatTableList(this.tableList),
        headers: [
          { label: "站点id", key: "id" },
          { label: "站点名称", key: "siteName" },
          { label: "行政区域", key: "region" },
          { label: "详细地址", key: "detailAddress" },
          { label: "充电桩总数", key: "siteNumber" },
          { label: "充电桩正常", key: "normalSiteNumber" },
          { label: "故障充电桩", key: "breakDownSiteNumber" },
          { label: "在线充电桩数", key: "onlineSiteNumber" },
          { label: "离线充电桩数", key: "offlineSiteNumber" },
          { label: "未注册充电桩", key: "unRegisterSiteNumber" },
          { label: "站点使用率", key: "useNumber" },
          { label: "创建时间", key: "createTime" },
        ],
        filename: "站点数据.xlsx",
      });
    },
    // 格式化表格数据
    formatTableList(data) {
      return data.map((item) => {
        return {
          ...item,
          createTime: this.parseTime(item.createTime),
          useNumber: item.useNumber ? item.useNumber.toFixed(1) + "%" : "-",
        };
      });
    },
    // 导出设备二维码
    async exportQrcode(row) {
      let { rows: stationsList } = await getStationListAPI({
        pageNum: "1",
        pageSize: "500",
        siteId: row.id,
      });

      let excelData = await Promise.all(
        stationsList.map(async (station) => {
          let deviceSerialNum = station.deviceSerialNum;

          // 创建二维码url数组
          let qrcodeTextList = [
            this.generateQRCodeBase64(
              `https://api-charge.znscxny.com/qrcode?stationSerialNumPort=${deviceSerialNum}`,
              deviceSerialNum
            ),
          ];
          let base64List = await Promise.all(qrcodeTextList);

          return {
            deviceSerialNum: deviceSerialNum,
            stationName: station.stationName,
            qrcode0: base64List[0],
          };
        })
      );

      console.log("excelData", excelData);

      let exportList = [];

      excelData.forEach((item) => {
        exportList.push({
          deviceSerialNum: item.deviceSerialNum,
          num: "",
          stationName: item.stationName,
          qrcode: item.qrcode0,
        });
      });

      console.log("excelData", exportList);

      setTimeout(() => {
        exportExcel({
          data: exportList,
          headers: [
            { key: "deviceSerialNum", label: "设备序列号" },
            { key: "num", label: "序号" },
            { key: "qrcode", label: "二维码" },
            { key: "stationName", label: "设备名称" },
          ],
          filename: row.siteName + "设备二维码",
          imageColumns: ["qrcode"],
          options: {
            width: 15,
            height: 80,
          },
        });
      }, 1000);
    },
    // 导出充电口二维码
    async exportQrcode2(row) {
      let { rows: stationsList } = await getStationListAPI({
        pageNum: "1",
        pageSize: "500",
        siteId: row.id,
      });

      let excelData = await Promise.all(
        stationsList.map(async (station) => {
          let deviceSerialNum = station.deviceSerialNum;

          // 创建二维码url数组
          let qrcodeTextList = [
            this.generateQRCodeBase64(
              `https://api-charge.znscxny.com/qrcode?stationSerialNumPort=${deviceSerialNum}`,
              deviceSerialNum
            ),
          ];
          for (let i = 1; i <= 10; i++) {
            qrcodeTextList.push(
              this.generateQRCodeBase64(
                `https://api-charge.znscxny.com/qrcode?stationSerialNumPort=${deviceSerialNum}&port=${i}`,
                deviceSerialNum
              )
            );
          }

          let base64List = await Promise.all(qrcodeTextList);

          return {
            deviceSerialNum: deviceSerialNum,
            stationName: station.stationName,
            qrcode1: base64List[1],
            qrcode2: base64List[2],
            qrcode3: base64List[3],
            qrcode4: base64List[4],
            qrcode5: base64List[5],
            qrcode6: base64List[6],
            qrcode7: base64List[7],
            qrcode8: base64List[8],
            qrcode9: base64List[9],
            qrcode10: base64List[10],
          };
        })
      );

      console.log("excelData", excelData);

      let exportList = [];

      excelData.forEach((item) => {
        for (let i = 1; i <= 10; i++) {
          exportList.push({
            deviceSerialNum: item.deviceSerialNum,
            num: i === 0 ? "" : i,
            stationName: item.stationName,
            qrcode: item[`qrcode${i}`],
          });
        }
      });

      console.log("excelData", exportList);

      setTimeout(() => {
        exportExcel({
          data: exportList,
          headers: [
            { key: "deviceSerialNum", label: "设备序列号" },
            { key: "num", label: "序号" },
            { key: "qrcode", label: "二维码" },
            { key: "stationName", label: "设备名称" },
          ],
          filename: row.siteName + "充电口二维码",
          imageColumns: ["qrcode"],
          options: {
            width: 15,
            height: 80,
          },
        });
      }, 1000);
    },
    async generateQRCodeBase64(text, qrText) {
      try {
        const qrcodeBase64 = await QRCode.toDataURL(text);

        const canvas = document.createElement("canvas");
        canvas.width = 300; // 设置宽度为 300 像素
        canvas.height = 300; // 设置高度为 300 像素
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.src = qrcodeBase64;

        return new Promise((resolve, reject) => {
          img.onload = () => {
            ctx.drawImage(img, 20, 20, 260, 260); // 在 canvas 上绘制图像

            // 添加黑色文字
            // ctx.font = "26px Arial";
            // ctx.fillStyle = "black";
            // ctx.textAlign = "center";
            // ctx.fillText(qrText, canvas.width / 2, canvas.height - 10);

            const base64Image = canvas.toDataURL("image/png");
            resolve(base64Image);
          };
        });
      } catch (error) {
        console.error("Error generating QR code:", error);
        throw error; // 重新抛出错误以便调用者处理
      }
    },
    // 编辑成功回调
    onEditSuccess() {
      this.editVisible = false;
      this.getList();
    },
    // 编辑关闭回调
    onEditCancel() {
      this.editVisible = false;
    },
    // 充电配置 编辑成功回调
    onGlobalChargeEditSuccess() {
      this.globalChargeVisible = false;
      this.getList();
    },
    // 充电配置 编辑关闭回调
    onGlobalChargeEditCancel() {
      this.globalChargeVisible = false;
    },
    // 系统设置 编辑成功回调
    onGlobalTcpConfigEditSuccess() {
      this.globalTcpVisible = false;
      this.getList();
    },
    // 系统设置 编辑关闭回调
    onGlobalTcpConfigEditCancel() {
      this.globalTcpVisible = false;
    },
    // 统计数据查询
    getStatistic() {
      getStatisticAPI({}).then((res) => {
        this.statisticInfo = res.data || {};
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getListAPI(this.queryParams).then((res) => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteAPI([row.id]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 跳转详情页 */
    toDetail(row) {
      this.$router.push({
        path: "site/edit",
        query: {
          id: row.id,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.divider {
  flex: none;
  height: 100px;
  width: 1px;
  background-color: #efefef;
}

.statistics-content {
  flex: 1 1 auto;
  width: 50%;
  flex-wrap: wrap;
  display: flex;

  .statistic-item {
    flex: none;
    width: 33%;
    margin: 10px 0;
  }
}
</style>
